import 'package:flutter/material.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/refreshable_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/click_address_event.dart';
import '../../event/refresh_order_event.dart';



class AddressPage extends StatefulWidget {
  /// 1: 需要回传参数 2：弹框
  int source;
  String missionNo;
  int missionNum;
  AddressPage(this.source,this.missionNo,this.missionNum, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return AddressPageState();
  }
}

class AddressPageState extends State<AddressPage> {
  dynamic _data;
  dynamic _addressTypeList;
  final RefreshableLayoutController _recyclerLayoutController = RefreshableLayoutController();
  final _inputController = TextEditingController(text: "");
  List _tabs = [];
  List _leftData = [];
  var _index = 0;
  var _yIndex = 0;
  String _searchKey = "";
  int _addressTypeId = 0;
  int _time = 1;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _inputController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        color: UIColor.color_main,
        child: Column(
          children: [
            _renderTitle(),
            _renderInput(),
            _searchKey == ""?_renderTab(context):0.wspace,
            const Divider(height: 1, thickness: 1, color: Colors.black12),
            Expanded(
                child: Row(
                  children: [
                    _searchKey == ""?_renderLeft(context):0.wspace,
                    Expanded(
                      child: Container(
                        height: MediaQuery.of(context).size.height,
                        padding: EdgeInsets.all(12.rpx),
                        decoration:  BoxDecoration(
                          color:  _searchKey == ""?UIColor.color_content:UIColor.color_t12, // 背景色
                        ),
                        child: _renderRightContent(),
                      ),)
                  ],
                )),
          ],
        ));
  }

   _getAddressType() {
     Api.getx(context, "/waybill/address_type", progress: false, success: (data) {
       _addressTypeList = data;
       List list = [];
       List array = [];
       data.forEach((item) {
         list.add(item["name"]);
       });
       data[_index]["children"].forEach((item) {
         array.add(item["name"]);
       });
       setState(() {
        if(list.isNotEmpty) {
          _tabs = list;
        }
        if (array.isNotEmpty) {
           _leftData = array;
        }

       });
     }, failTip: "获取数据失败", fail: (_) {

     });
  }

  Widget _renderTitle() {
    return Container(
      color: UIColor.color_content,
      width: double.infinity,
      height: MediaQuery.of(context).padding.top + 44.rpx,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child: Stack(
        children: [
          SizedBox(
            width: 50.rpx,
            child: IconButton(
              iconSize: 18.rpx,
              icon: const Icon(
                Icons.arrow_back_ios_new,
                color: UIColor.color_t1,
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ),
          Center(
              child: UText.get("地址库", Colors.black, 16.rpx, fw: FontWeight.w600)
                  .center),
        ],
      ),
    );
  }

  Widget _renderInput() {
    return Container(
      color: UIColor.color_content,
      padding: EdgeInsets.symmetric(vertical: 4.rpx, horizontal: 16.rpx),
      child: TextField(
        controller: _inputController,
        style: TextStyle(color: UIColor.color_t1, fontSize: 14.rpx),
        textInputAction: TextInputAction.search,
        maxLength: 30,
        onChanged: (text) {
          setState(() {
            _searchKey = _inputController.text;
          });

          _recyclerLayoutController.reload();
        },
        decoration: InputDecoration(
            counterText: "",
            contentPadding:
            EdgeInsets.symmetric(vertical: 8.rpx, horizontal: 12.rpx),
            isCollapsed: true,
            border: OutlineInputBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(2.rpx),
                ),
                borderSide: BorderSide.none),
            prefixIcon: Padding(
              padding: EdgeInsets.only(left: 10.rpx, right: 4.rpx, top: 3.rpx),
              child: Icon(
                Icons.search,
                size: 18.rpx,
                color: Colors.black.withOpacity(0.4),
              ),
            ),
            prefixIconConstraints: BoxConstraints(maxHeight: 22.rpx),
            hintText: "关键词搜索",
            hintStyle: TextStyle(
                color: Colors.black.withOpacity(0.4), fontSize: 14.rpx),
            filled: true,
            fillColor: UIColor.color_input),
      ),
    );
  }

  Widget _renderTab(context) {
    return  Container(
        color: UIColor.color_content,
        child: ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 48.rpx),
            child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: _tabs.length,
                itemBuilder: _renderTabItem))
    );
  }

  Widget _renderTabItem(BuildContext context, int index) {
    var color = _index == index ? UIColor.color_primary : Colors.black.withOpacity(0.6);
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          _index = index;
          _yIndex = 0;
          List array = [];
          _addressTypeList[_index]["children"].forEach((item) {
            array.add(item["name"]);
          });
          setState(() {
            _leftData = array;
            _addressTypeId = _addressTypeList[_index]["children"].length == 0?_addressTypeList[_index]["id"] : _addressTypeList[_index]["children"][0]["id"] ;
          });
          _recyclerLayoutController.reload();
        },
        child: Padding(
            padding: EdgeInsets.only(right: 15.rpx, left: 15.rpx),
            child: Column(
                children: [
                  12.hspace,
                  Text(_tabs[index],
                      style: TextStyle(
                          color: color,
                          fontSize: 16.rpx,
                          fontWeight: FontWeight.w600)),
                  3.hspace,
                  Container(
                    width: 24.rpx,
                    height: 4.rpx,
                    decoration: BoxDecoration(
                      color: _index == index
                          ? UIColor.color_primary
                          : Colors.transparent,
                      borderRadius: BorderRadius.all(Radius.circular(3.rpx)),
                    ),

                  ),
                ])
        )
    );
  }

  Widget _renderLeft(context) {
    return Container(
        width: 100.rpx,
        height: double.infinity,
        color: const Color(0xffE7E7E7),
        child: MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: ListView.builder(
              itemCount: _leftData.length,
              itemBuilder: _renderLeftItem,
              shrinkWrap: true,
            )
        )
    );
  }

  Widget _renderLeftItem(BuildContext context, int index) {
    var color = _yIndex == index
        ? UIColor.color_primary
        : Colors.black.withOpacity(0.6);

    var bg = _yIndex == index ? Colors.white : const Color(0xffE7E7E7);

    var borderColor =
    _yIndex == index ? UIColor.color_primary : const Color(0xffE7E7E7);

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        setState(() {
          _yIndex = index;
          _addressTypeId = _addressTypeList[_index]["children"].length == 0?_addressTypeList[_index]["id"] : _addressTypeList[_index]["children"][_yIndex]["id"] ;
        });
        _recyclerLayoutController.reload();
      },

      child: Container(
        padding: EdgeInsets.only(top: 16.rpx, bottom: 16.rpx),
        decoration: BoxDecoration(
            color: bg,
            border: Border(
                left: BorderSide(
                  color: borderColor,
                  width: 2.rpx,
                ))),
        child: UText.get(_leftData[index], color, 16.rpx,
            fw: FontWeight.w600, textAlign: TextAlign.center),
      ),
    );
  }

  Widget _renderRightContent() {
    if(_time == 1) {
      _getAddressType();
    }
    _time += 1;
    return
        SizedBox(
          height: double.infinity,
          child: Column(
            children: [
              RefreshableLayout(
                controller: _recyclerLayoutController,
                urlCallback: _buildUrl,
                itemBuilder: _renderRightList,
                dataCallback: _dataCallback,
              ).expand,
            ],
          )
        );
  }

  String _buildUrl() {
    var id = _searchKey ==""?_addressTypeId:0;
    var baseUrl = "/waybill/address_book?address_type_id=$id";
    var searchKey = _inputController.text.trim();
    if (searchKey.isNotEmpty) {
      if (!baseUrl.contains("?")) {
        baseUrl += "?";
      } else {
        baseUrl += "&";
      }
      baseUrl += "search_key=${Uri.encodeComponent(searchKey)}";
    }
    return baseUrl;
  }

  _dataCallback(dynamic data)  {
    List list = [];
    if(_searchKey != "") {
      data["list"].forEach((item) => {
        item["title1"] = item["alias_name"].indexOf(_searchKey) ==-1?item["alias_name"]:item["alias_name"].indexOf(_searchKey) == 0?'':item["alias_name"].substring (0,item["alias_name"].indexOf(_searchKey)),
        item["title2"] = item["alias_name"].indexOf(_searchKey) ==-1?'':item["alias_name"].indexOf(_searchKey) == 0?_searchKey:_searchKey,
        item["title3"] = item["alias_name"].indexOf(_searchKey) ==-1?'':item["alias_name"].indexOf(_searchKey) == 0?item["alias_name"].substring(item["alias_name"].indexOf(_searchKey)+_searchKey.length):item["alias_name"].indexOf(_searchKey) == item["alias_name"].length?'':item["alias_name"].substring(item["alias_name"].indexOf(_searchKey)+_searchKey.length),
        list.add(item),
      });
    }
    _data = list;
  }

  Widget _renderRightItem(data, int index) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
          padding: EdgeInsets.symmetric(vertical: 12.rpx, horizontal: 16.rpx),
          margin:EdgeInsets.only(bottom: 10.rpx),
          decoration: BoxDecoration(
              color: UIColor.color_content,
              border: Border.all(width: 1.rpx,color: _searchKey == ""? const Color(0xffE7E7E7): UIColor.color_content),
              borderRadius: const BorderRadius.all(Radius.circular(16.0))
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _searchKey == ""?UText.get(data["alias_name"] != "" ? data["alias_name"] : "", UIColor.color_t1, 16.rpx, fw: FontWeight.w600):
                  RichText(
                    text: TextSpan(
                      text: data["title1"],
                      style: TextStyle(
                        color: UIColor.color_t1,
                        fontSize: 16.rpx,
                        fontWeight:FontWeight.w600
                      ),
                      children: [
                        TextSpan(text: data["title2"], style:  TextStyle(color: UIColor.color_primary,fontSize: 16.rpx,fontWeight:FontWeight.w600)),
                        TextSpan(text: data["title3"], style:  TextStyle(color: UIColor.color_t1,fontSize: 16.rpx,fontWeight:FontWeight.w600)),
                      ],
                    ),
                  ),
                  _searchKey == ""?0.wspace:
                  SizedBox(
                    width: 80.rpx,
                    child: UText.get(data["address_type_show"] != "" ? data["address_type_show"] :"", UIColor.color_t1, 12.rpx),
                  ),
                ],
              ),
              4.hspace,
              UText.get(data["station_name"] != "" ? data["station_name"] : "", UIColor.color_t7, 14.rpx,textAlign:TextAlign.left,),
            ],
          )
      ),
      onTap: () {
        if(widget.source == 1) {
          eventBus.fire(ClickAddressEvent(
            data["lat"],
            data["lng"],
            data["alias_name"],
            data["alias_id"],
            data["station_name"],
            data["station_id"]));
          Navigator.of(context).pop();
        }
        if(widget.source == 2) {
          showDialog(
            context: context,
            builder: (context) {
              return Dialog(
                  backgroundColor:Colors.transparent,
                  child: Container(
                    width: 320.rpx,
                    //height: 244.rpx,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
                    ),
                    child: Column(
                      children: [
                        20.hspace,
                        UText.get("确认变更收货地址吗？", UIColor.color_black, 16.rpx,fw: FontWeight.bold),
                        20.hspace,
                        Container(height: 0.5.rpx, color: UIColor.color_divider),
                        widget.missionNum > 1?
                        TextButton(onPressed: () {
                          print("同步到所有任务");
                          changeDestination(data,1);
                        }, child: UText.get("同步到所有任务", UIColor.color_primary, 16.rpx)):0.wspace,
                        Container(height: 0.5.rpx, color: UIColor.color_divider),
                        TextButton(onPressed: () {
                          print("仅本任务变更");
                          changeDestination(data,0);
                        }, child: UText.get( widget.missionNum >1?"仅本任务变更":"变更收货地址", UIColor.color_primary, 16.rpx)),
                        Container(height: 0.5.rpx, color: UIColor.color_divider),
                        2.hspace,
                        MaterialButton(
                            child: UText.get("取消", UIColor.color_t13, 16.rpx,fw: FontWeight.bold),
                            onPressed: () {
                              Navigator.of(context).pop();
                            }).size(56.rpx, double.infinity),
                      ],
                    ),
                  ).intrinsicHeight
              );
            },
          );
          // showDialog(
          //     context: context,
          //     barrierDismissible: false,
          //     builder: (BuildContext context) {
          //       return StatefulBuilder(
          //           builder: (BuildContext context,void Function(void Function()) setState) {
          //             return SimpleDialog(
          //                 contentPadding: const EdgeInsets.fromLTRB(0.0, 32.0, 0.0, 0.0),
          //                 title: UText.get("确认变更收货地址吗？", UIColor.color_t1, 16.rpx, fw: FontWeight.w600,textAlign:TextAlign.center),
          //                 children: [
          //                   widget.missionNum >1?
          //                   Container(
          //                     decoration:  const BoxDecoration(
          //                         border: Border(
          //                             top: BorderSide(
          //                                 width: 1,
          //                                 color: Color(0xFFDCDCDC)
          //                             )
          //                         )
          //                     ),
          //                     child: TextButton(onPressed: () {
          //                       print("同步到所有任务");
          //                       changeDestination(data,1);
          //                     }, child: UText.get("同步到所有任务", UIColor.color_primary, 16.rpx)),
          //                   ):0.wspace,
          //                   Container(
          //                     decoration:  const BoxDecoration(
          //                         border: Border(
          //                             top: BorderSide(
          //                                 width: 1,
          //                                 color: Color(0xFFDCDCDC)
          //                             )
          //                         )
          //                     ),
          //                     child: TextButton(onPressed: () {
          //                       print("仅本任务变更");
          //                       changeDestination(data,0);
          //                     }, child: UText.get( widget.missionNum >1?"仅本任务变更":"变更收货地址", UIColor.color_primary, 16.rpx)),
          //                   ),
          //                   Container( height: 1.rpx, color: UIColor.color_divider),
          //                   Row(
          //                     mainAxisAlignment: MainAxisAlignment.spaceAround,
          //                     children: [
          //                       Container(
          //                         height:56.rpx,
          //                         padding: EdgeInsets.symmetric(horizontal: 38.rpx),
          //                         child: TextButton(onPressed: () {
          //                           Navigator.pop(context);
          //                         }, child: UText.get("取消", UIColor.color_t13, 16.rpx)),
          //                       )
          //                     ],
          //                   )
          //                 ]
          //             );
          //           }
          //       );
          //     }
          // );
        }
      },
    );
  }

   void changeDestination(dynamic data,int type) {
    var dialog = LoadingDialog(context);
    dialog.show(text: "同步中...");
    String stationName = data["alias_name"]!=""?"(" + data["station_name"] + ")":data["station_name"];
    var json = {};
    json["mission_no"] = widget.missionNo;
    json["delivery_station_id"] = data["station_id"];
    json["delivery_station_name"] = data["station_name"];
    json["delivery_address"] = data["alias_name"] + stationName;
    json["delivery_station_alias_id"] = data["alias_id"];
    json["delivery_station_alias_name"] = data["alias_name"];
    json["is_all"] = type;
    // json["delivery_lng"] = data["lat"];
    // json["delivery_lat"] = data["lng"];
    json["full"] = false;
    print(json);
    Api.submitx(context, "/waybill_mission/change_destination", data: json, progress: false, success: (data) {
      dialog.hide();
      Navigator.pop(context);
      Navigator.of(context).pop();
      eventBus.fire(RefreshOrderEvent());
    }, failTip: "提交失败", fail: (_) {
      dialog.hide();
    });
  }

  Widget _renderRightList(dynamic data,int index) {
    return _renderRightItem(data,index);
  }

}
